/**
 * http://usejsdoc.org/
 * @class session
 * @desc session 与 cookie 
 */
var session,sessions;

function newSession(res){
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	var SESSID = '';
	for (var i = 0; i < 40; i++) {
		var rnum = Math.floor(Math.random()*chars.length);
		SESSID +=chars.substring(rnum, rnum+1);
	}//generate a 40 char random string for session id
	if(typeof sessions[SESSID] !== 'undefined'){//判断是否存在session
		return newSession(res); //Avoid dupliate session
	}
	
	var dt = new Date();
	dt.setMinutes(dt.getMinutes()+30);
	
	var session = {
		SESSID:SESSID,
		expires:dt
	};
	
	sessions[SESSID] = session; // store it for future reuqests
	res.setHeader('Set-Cookie','SESSID='+SESSID);
	
	return session;
}

function cleanSession(res){
	for (var sess in sessions) {
		if(sess.expires < Date()){
			delete sessions[sess.SESSID];
		}
	}
}

var start = function(res,req){
	var conn = {res:res,req:req};
	var cookies = {};
	
	if(typeof conn.req.headers.cookie !== 'undefined'){//判断是否存在cookie
		conn.req.headers.cookie.split(';').forEach(function(cookie) {
			var parts = cookie.split('=');
			cookies[parts[0].trim()] = (parts[1] || '').trim();
		});//Grab all cookies,and parse them into properties of the cookies object
	}else{
		cookies.SESSID = 0;
	}
	
	var SESSID = cookies.SESSID;
	if(typeof sessions[SESSID] !== 'undefined'){//判断是否存在session
		session = sessions[SESSID];
		if(session.expires < Date()){ //if session is expired
			delete session[SESSID];
			return newSession(conn.res);
		}else{
			var dt = new Date();
			dt.setMinutes(dt.getMinutes() + 30);
			session.expires = dt;//reset session expiration
			return sessions[SESSID];
		}
	}
};

exports.start = start;